<?php
/**
 *
 * 公共函数
 *
 * @author		Tata <windzb@qq.com>
 */


// ------------------------------------------------------------------------
/*
 * 对象转数组
 */

function o2a ($obj)
{
	$arr = array();
	$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
	foreach ($_arr as $key => $val)
	{
		$val = (is_array($val) || is_object($val)) ? o2a($val) : $val;
		$arr[$key] = $val;
	}
	return $arr;
}

//保存缓存
function ccSave($key,$val='',$time=3600)
{
	if(DEV_MODE == 'local') {
		include_once(LIBS_PATH . "/Memcached.php");
		$mem = new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);

    }else{
		$mem =new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);
		$mem->setSaslAuthData(MEM_USER, MEM_PWD);
	}


	//$mem->setSaslAuthData(MEM_USER, MEM_PWD);
	//$mem->connect('localhost',11211);
	$mem->set($key,$val, $time);

	//global $cacheService;
	//return $cacheService->set($key,$val,$time);
}
//获取缓存
function ccLoad($key)
{
	if(DEV_MODE == 'local') {
		include_once(LIBS_PATH . "/Memcached.php");
		$mem = new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);

	}else{
		$mem =new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);
		$mem->setSaslAuthData(MEM_USER, MEM_PWD);
	}

	//$mem->setSaslAuthData(MEM_USER, MEM_PWD);
	//$mem->connect('localhost',11211);
	$ret =$mem->get($key);
	return $ret;
	//global $cacheService;
	//return $cacheService->get($key);
}
//清理缓存
function ccDel($key)
{
	if(DEV_MODE == 'local') {
		include_once(LIBS_PATH . "/Memcached.php");
		$mem = new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);
	}else{
		$mem =new Memcached;
		$mem->setOption(Memcached::OPT_COMPRESSION, false);
		$mem->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$mem->addServer(MEM_HOST, 11211);
		$mem->setSaslAuthData(MEM_USER, MEM_PWD);

        /*$config = array(
            'host'  => MEM_HOST,
            'port'  => '11211',
            'username' => MEM_USER,
            'password' => MEM_PWD,
            'endpoint' => '', # 对于青岛机房的 ocs 实例时可以配置, 其它类型 ocs 可以不配置, 忽略此项
        );
        $mem = Alibaba::cache($config);*/
	}

	//$mem->setSaslAuthData(MEM_USER, MEM_PWD);
	//$mem->connect('localhost',11211);
	$mem->delete($key);

	//global $cacheService;
	//return $cacheService->delete($key);
}

// --------------------------------------------------------------------

/**
 * Keeps track of which libraries have been loaded.  This function is
 * called by the load_class() function above
 *
 * @access	public
 * @return	array
 */
if ( ! function_exists('is_loaded'))
{
	function is_loaded($class = '')
	{
		static $_is_loaded = array();

		if ($class != '')
		{
			$_is_loaded[strtolower($class)] = $class;
		}

		return $_is_loaded;
	}
}


// ------------------------------------------------------------------------
/*
 * 打印出变量
 */
function dump ($array)
{
	echo "<pre>". print_r($array, TRUE). "</pre>";
}


// ------------------------------------------------------------------------
/*
 * 打印出全部变量
 */
function dump_all()
{
	echo '<pre>';
	var_dump($GLOBALS);
	echo '</pre>';
}


// ------------------------------------------------------------------------
/*
 * 防刷新
 * $sec 默认1秒
 */

function defresh($sec = 1){
	global $cacheService;

	$ip = getRealIp();

	if($cacheService->get($ip))
	{
		return false;
	}
	else
	{
		$cacheService->set($ip,$ip,$sec);
		return true;
	}
}


// ------------------------------------------------------------------------
/*
 * 得到访问者IP
 */

function getRealIp()
{
	$ip=false;
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
		if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
		for ($i = 0; $i < count($ips); $i++) {
			if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
				$ip = $ips[$i];
				break;
			}
		}
	}
	return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

// ------------------------------------------------------------------------
/*
 * 字符串 时间比较  1 < 2 为 真
 */
function CompareDate_str($time_1, $time_2 = '')
{
	$time_2 = $time_2 ? $time_2 : date('Y-m-d H:i:s');	//time_2默认为当前时间
	if(strtotime($time_1) < strtotime($time_2))
		return TRUE;
	else
		return FALSE;
}

// ------------------------------------------------------------------------
/*
 * 时间戳 时间比较  1 < 2 为 真
 */
function CompareDate_timestamp($time_1, $time_2)
{
	if($time_1 < $time_2)
		return TRUE;
	else
		return FALSE;
}

// ------------------------------------------------------------------------
/*
 * 格式化数字,避免数字过大时被自动转换为科学计数法
 */
function num_format($numb)
{
	$numb = $numb*1;
	$numb = number_format($numb);
	return str_replace(',','',$numb);
}
// ------------------------------------------------------------------------
/*
 * 获取文件后缀名
 * @param string $type =  B or C
 */
function get_extension($filename)
{
	if (($pos = strrpos($filename, ".")) === FALSE)
	{
		return FALSE;
	}
	else
	{
		$extension = substr($filename, $pos + 1);
		return $extension; // will echo like "jpeg"  返回结果没有 点 .
	}
}

// ------------------------------------------------------------------------
/*
 * 把unicode中的中文编码转成中文
 *
 */
function deunicode($str)
{
	//线上无create_function方法..
	//$str =  html_entity_decode($str);
	//return preg_replace_callback("/&#(\d+);/" ,create_function('$matches','return chr($matches[1]);'),$str);

	return htmlspecialchars_decode($str);
}

// ------------------------------------------------------------------------
/*
 * 隐私保护  把部分字符串替换为星号
 *
 */
function star_replace($str)
{
	//$len = strlen($str)/2;
	//return substr_replace($str,str_repeat('*',$len),ceil(($len)/2),$len);
	$len = strlen($str);
	$max_len = ($len >2) ? ($len -2) : 1;
	$star_numb = ceil(($len)/4);
	$star_numb = ($star_numb<3)? 3 :$star_numb;
	return substr_replace($str,str_repeat('*',$star_numb),1,$max_len);
}

// ------------------------------------------------------------------------
/*
 * 隐私保护  把部分字符串替换为先生
 *
 */
function mixnick_replace($mixstr)
{
	return substr_replace($mixstr,"**",1,strlen($mixstr));
}

// ------------------------------------------------------------------------
/*
 * 过滤HTML标签
 *
 */
function html_filter($str) {
	$search = array ("'<script[^>]*?>.*?</script>'si", // 去掉 javascript
		"'<style[^>]*?>.*?</style>'si", // 去掉 css
		"'<[/!]*?[^<>]*?>'si", // 去掉 HTML 标记
		"'<!--[/!]*?[^<>]*?>'si", // 去掉 注释标记
		"'([rn])[s]+'", // 去掉空白字符
		"'&(quot|#34);'i", // 替换 HTML 实体
		"'&(amp|#38);'i",
		"'&(lt|#60);'i",
		"'&(gt|#62);'i",
		"'&(nbsp|#160);'i",
		"'&(iexcl|#161);'i",
		"'&(cent|#162);'i",
		"'&(pound|#163);'i",
		"'&(copy|#169);'i",
		"'&#(d+);'e"); // 作为 PHP 代码运行
	$replace = array ("",
		"",
		"",
		"",
		"\1",
		"\"",
		"&",
		"<",
		">",
		" ",
		chr(161),
		chr(162),
		chr(163),
		chr(169),
		"chr(\1)");
	//$str 为需要处理字符串，如果来源为文件可以 $str = file_get_contents($filename);
	return preg_replace($search, $replace, $str);
}

// ------------------------------------------------------------------------
/*
 * 生成默认选择框的分钟
 * @ add_one_minute =0 为当前时间 =1 为加10分钟
 * @ theMinute 为传入的分钟数,用来确定选中项
 */
function echo_select_minute($add_one_minute = 0,$theMinute)
{
	$str = '';

	for($i=0;$i<60;$i++)
	{
		if(empty($theMinute))
		{
			if($add_one_minute == 1)
			{
				$nowMinute = date( "i",strtotime("+10 minutes"));	//结束时间默认加十分钟
			}
			else
			{
				$nowMinute = date( "i");
			}
		}
		else
		{
			$nowMinute = $theMinute;
		}

		if( $i == $nowMinute)
		{
			$selected = ' selected="selected"';
		}
		else
		{
			$selected = '';
		}

		if($i<10)
		{
			$str .= '<option  value="0'.$i.'" '.$selected.'>0'.$i.'</option>';
		}
		else
		{
			$str .= '<option  value="'.$i.'" '.$selected.'>'.$i.'</option>';
		}
	}
	return $str;
}

// ------------------------------------------------------------------------
/*
 * 生成默认选择框的小时
 * @ add_one_hour =0 为当前时间 =1 为加一小时
 * @ theHour 为传入的小时数,用来确定选中项
 */
function echo_select_hour($add_one_hour = 0,$theHour)
{
	$str = '';

	for($i=0;$i<24;$i++)
	{
		if(empty($theHour))
		{
			if($add_one_hour == 1)
			{
				$nowHour = date("H",strtotime("+1 hours"));	//结束时间默认加一小时
			}
			else
			{
				$nowHour = date( "H");
			}
		}
		else
		{
			$nowHour = $theHour;
		}

		if( $i == $nowHour)
		{
			$selected = ' selected="selected"';
		}
		else
		{
			$selected = '';
		}

		if($i<10)
		{
			$str .= '<option  value="0'.$i.'" '.$selected.'>0'.$i.'</option>';
		}
		else
		{
			$str .= '<option  value="'.$i.'" '.$selected.'>'.$i.'</option>';
		}
	}
	return $str;
}



//函数名: compress_html
//参数: $string
//返回值: 压缩后的$string
function compress_html($string) {
	$string = str_replace("\r\n", '', $string); //清除换行符
	$string = str_replace("\n", '', $string); //清除换行符
	$string = str_replace("\t", '', $string); //清除制表符
	$pattern = array (
		"/> *([^ ]*) *</", //去掉注释标记
		"/[\s]+/",
		"/<!--[\\w\\W\r\\n]*?-->/",
		"/\" /",
		"/ \"/",
		"'/\*[^*]*\*/'"
	);
	$replace = array (
		">\\1<",
		" ",
		"",
		"\"",
		"\"",
		""
	);
	return preg_replace($pattern, $replace, $string);
}



function md5String(){
	return md5(md5(time().md5( rand(rand(1,800),100000))));

}
////////////////// 获取TAE环境下的用户信息 /////////////////

//获取卖家ID
function get_seller_id()
{
	$seller_id = 0;

	return $seller_id;
}
//获取卖家nick
function get_seller_nick()
{
	$seller_nick = '';

	return $seller_nick;
}
//获取买家混淆nick
function get_buyer_mix_nick()
{
	$buyer_mix_nick = '';

	return $buyer_mix_nick;
}


//一个简易的数字混淆
function n_encode($n,$k1=8642138,$k2=7896123){
	return ($n ^ $k1 ^ $k2) ^ ($k1 - $k2);
};
function n_decode($n,$k1=8642138,$k2=7896123){
	return ($n ^ ($k1 - $k2)) ^ $k1 ^ $k2;
};